package com.uncheck;

/**
 * AIKA
 * 动态执行定时任务
 */


import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.text.SimpleDateFormat;
import java.util.Date;

@Slf4j
public class ScheduleTask {


    public void startSchedule(Date startTime, Date endTime, long intervalseconds, Runnable task) {
        //立马执行一次,或者 +intervalseconds
        long delay = startTime.getTime() - System.currentTimeMillis();
        long duration = endTime.getTime() - startTime.getTime();
        ScheduledExecutorService executorService = Executors.newScheduledThreadPool(2);
        executorService.scheduleAtFixedRate(() -> {
            long now = System.currentTimeMillis();
            if (now < endTime.getTime()) {
                    task.run();
            } else {
                executorService.shutdown();
            }
        }, delay < 0 ? 0 : delay, intervalseconds, TimeUnit.MILLISECONDS);
    }

    public static void main(String[] args) throws Exception {
        ScheduleTask scheduler = new ScheduleTask();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date startTime = sdf.parse("2024-07-18 9:40:30");
        Date endTime = sdf.parse("2054-07-19 20:00:00");

        //每5s执行一次
        long intervalInMilliseconds = 5 * 1000;

        System.out.println("任务启动,当前时间:"+new Date());
        Runnable task = () -> {
            System.out.println("Executing task at " + new Date());
        };

        scheduler.startSchedule(new Date(), endTime, intervalInMilliseconds, task);
    }
}
